import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { getToken } from "@/util/auth";
import { message } from "ant-design-vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login.vue"),
  },
  {
    path: "/",
    redirect: "/home",
    component: () => import("@/components/layout.vue"),
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("@/views/home/the-slider.vue"),
        children: [
          {
            path: "", //默认是/home
            name: "welcome",
            component: () => import("@/views/home/welcome.vue"),
          },
          {
            // 前缀加了/ 那个可以直接显示（不需要/home/...）
            path: "/booksMessage/:level2_id",
            name: "booksMessage_l2_id",
            component: () => import("@/views/home/booksMessage.vue"),
          },
          {
            path: "/booksMessage/:level2_id/:ebookId",
            name: "docByebookId",
            component: () => import("@/views/home/docByebookId.vue"),
          },
        ],
      },
      {
        path: "/userManage",
        name: "userManage",
        component: () => import("@/views/userManage/userManage.vue"),
        meta: { navTitle: "用户管理" },
      },
      {
        path: "/ebookManage",
        name: "ebookManage",
        component: () => import("@/views/ebookManage/ebookManage.vue"),
        meta: { navTitle: "电子书管理" },
      },
      {
        path: "/doc/:ebookId",
        name: "doc",
        component: () => import("@/views/ebookManage/doc.vue"),
      },

      {
        path: "/cateManage",
        name: "cateManage",
        component: () => import("@/views/cateManage/cateManage.vue"),
        meta: { navTitle: "分类管理" },
      },
      {
        path: "/about",
        name: "about",
        component: () => import("@/views/about/about.vue"),
        meta: { navTitle: "关于我们" },
      },
    ],
  },
  {
    path: "/:patchMatch(.*)",
    component: () => import("@/views/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  // console.log(to.path, getToken());
  // 没登陆 返回登录页
  if (getToken()) {
    next();
  } else if (to.path !== "/login") {
    message.warn("未登录/登录失效!");
    setTimeout(() => {
      next("/login");
    }, 500);
  } else {
    next();
  }
});
export default router;
